package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeQuestion;
import com.jdy.haoduoai.model.LeQuestionAnswer;
import com.jdy.haoduoai.model.LeQuestionWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

//import com.jdy.haoduoai.R;

/**
 * 专业测试题
 * 
 * @author hf
 * 
 */
@SuppressLint({ "ShowToast", "InflateParams" })
public class AbilityTestActivity extends com.jdy.haoduoai.activity.BaseActivity implements
    OnClickListener {

  @InjectView(id = R.id.testprogress)
  private ProgressBar progressBar;
  @InjectView(id = R.id.titlelyt)
  private LinearLayout titlelyt;
  @InjectView(id = R.id.layout_test)
  private LinearLayout layout_test;
  @InjectView(id = R.id.topic)
  private TextView topic;
  @InjectView(id = R.id.img_bg)
  private ImageView img_bg;
  @InjectView(id = R.id.btn_next, click = true)
  private Button btn_next;

  private int pager = 0; // 题目页码
  private int totoalQuestionNum;

  private LeQuestionWrapper mLeQuestionWrapper;
  private RadioGroup radioGroup; // 点选按钮组
  // private LeTestResult mTestResultDetail;

  private JSONArray jsonList = new JSONArray();
  private int question_id, id;

  private boolean isregisterflow, iscontinuetest, startActivityForResult;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.abilitytest);

    init();

    if (iscontinuetest) {
      loadContinueTestQuestions();
    } else {
      loadTestQuestions();
    }
  }

  private void init() {
    setNextButtonEnable(false);

    Intent it = getIntent();
    if (it != null) {
      isregisterflow = it.getBooleanExtra("registerflow", false);
      iscontinuetest = it.getBooleanExtra("continuetest", false);
      startActivityForResult = it.getBooleanExtra("startActivityForResult",
          false);
    }

    mBackImageButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {

        if (question_id == 0 && id == 0) {
          finish();
        } else {
          saveTestProgress();
        }
      }
    });
  }

  private void saveTestProgress() {
    if (question_id == 0 && id == 0) {
      return;
    }

    new CustomAsyncTask(this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {

        if (result.isSuccess()) {
          Intent it = new Intent(AbilityTestActivity.this,
              com.jdy.haoduoai.activity.AbilityTestExplainActivity.class);
          it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
              | Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(it);

        } else {
          toastShow(result.data);
        }

        finish();

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("result", jsonList);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/growth_test/unfinished", param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();

  }

  private void setNextButtonEnable(boolean enable) {
    if (enable) {
      btn_next.setEnabled(true);
      btn_next.setBackgroundColor(0xfff6d359);
      btn_next.setTextColor(0xfff94b15);

      btn_next.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    } else {
      btn_next.setEnabled(false);
      btn_next.setBackgroundColor(0xffc2c2c2);
      btn_next.setTextColor(0xffffffff);
    }
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      if (question_id == 0 && id == 0) {
        return super.onKeyDown(keyCode, event);
      } else {
        saveTestProgress();
        return true;
      }
    }
    return super.onKeyDown(keyCode, event);
  }

  private ImageLoader mImageLoader;

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mImageLoader = null;
  }

  @SuppressWarnings("deprecation")
  private void updateRadioBtnContent(final int questionIndex) {
    layout_test.removeAllViews();
    radioGroup.removeAllViews();

    if (mLeQuestionWrapper == null || mLeQuestionWrapper.questions.isEmpty()) {
      return;
    }

    final LeQuestion ques = mLeQuestionWrapper.questions.get(questionIndex);
    topic.setText((questionIndex + 1) + "、" + ques.content);
    if (Tools.isNotEmpty(ques.img)) {
      if (img_bg.getDrawable() != null) {
        Picasso.with(this).load(ques.img).placeholder(img_bg.getDrawable())
            .into(img_bg, new Callback() {

              @Override
              public void onError() {
                if (mImageLoader == null) {
                  mImageLoader = new ImageLoader(AbilityTestActivity.this);
                }
                mImageLoader.DisplayImage(ques.img, img_bg, false);
              }

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub

              }

            });
      } else {
        Picasso.with(this).load(ques.img).into(img_bg, new Callback() {

          @Override
          public void onSuccess() {
            // TODO Auto-generated method stub

          }

          @Override
          public void onError() {
            if (mImageLoader == null) {
              mImageLoader = new ImageLoader(AbilityTestActivity.this);
            }
            mImageLoader.DisplayImage(ques.img, img_bg, false);
          }
        });
      }
    }

    for (int i = 0; i < ques.answers.size(); i++) {
      final LeQuestionAnswer ans = ques.answers.get(i);

      RadioButton radio = new RadioButton(AbilityTestActivity.this);
      radio.setText(ans.content);
      radio.setTextColor(0xff595757);
      // radio.setButtonDrawable(null);

      Bitmap a = null;
      radio.setButtonDrawable(new BitmapDrawable(a));

      Drawable drawable = getResources().getDrawable(R.drawable.search_radio_2);
      drawable.setBounds(0, 0, drawable.getMinimumWidth(),
          drawable.getMinimumHeight());
      radio.setCompoundDrawables(drawable, null, null, null);

      radio.setCompoundDrawablePadding(Tools.getPixelByDip(this, 10));

      radio
          .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
              if (isChecked) {
                question_id = ans.question_id;
                id = ans.id;

                setNextButtonEnable(true);
              }
            }
          });

      radioGroup.addView(radio);
    }

    layout_test.addView(radioGroup);
  }

  private void loadContinueTestQuestions() {
    showloading("");
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {

        if (result.isSuccess()) {
          if (Tools.isNotEmpty(result.data)) {
            mLeQuestionWrapper = JsonSerializer.getInstance().deserialize(
                result.data, LeQuestionWrapper.class);

            if (Tools.isNotEmpty(mLeQuestionWrapper)) {
              totoalQuestionNum = mLeQuestionWrapper.questions.size();
              setTitle(mLeQuestionWrapper.info);
              progressBar.setMax(10 * totoalQuestionNum);
              // progressBar.setProgress(10);

              for (int i = 0; i < mLeQuestionWrapper.questions.size(); i++) {
                LeQuestion lq = mLeQuestionWrapper.questions.get(i);
                if (Tools.isNullStr(lq.answer_id) || lq.answer_id == 0) {
                  pager = i;
                  break;
                } else {
                  JSONObject jsonObjCheck = new JSONObject();

                  try {
                    jsonObjCheck.put("question_id", lq.id + "");
                    jsonObjCheck.put("answer_id", lq.answer_id + "");
                    jsonList.put(jsonObjCheck);
                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
              }

              if (pager == totoalQuestionNum - 1) {
                btn_next.setText("提交");
              }

              progressBar.setProgress(10 * (pager + 1));

              if (!mLeQuestionWrapper.questions.isEmpty()) {
                topic.setText(mLeQuestionWrapper.questions.get(pager).content);
              }
            }

            if (radioGroup == null) {
              radioGroup = new RadioGroup(AbilityTestActivity.this);
            }

            updateRadioBtnContent(pager);
          }
        } else {
          toastShow(result.data);
          setTitle("生长发育测评");
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/growth_test/continue", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void loadTestQuestions() {
    showloading("");
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {

        if (result.isSuccess()) {
          if (Tools.isNotEmpty(result.data)) {
            mLeQuestionWrapper = JsonSerializer.getInstance().deserialize(
                result.data, LeQuestionWrapper.class);

            if (Tools.isNotEmpty(mLeQuestionWrapper)) {
              totoalQuestionNum = mLeQuestionWrapper.questions.size();
              setTitle(mLeQuestionWrapper.info);
              progressBar.setMax(10 * totoalQuestionNum);
              progressBar.setProgress(10);
              if (!mLeQuestionWrapper.questions.isEmpty()) {
                topic.setText(mLeQuestionWrapper.questions.get(0).content);
              }
            }

            if (radioGroup == null) {
              radioGroup = new RadioGroup(AbilityTestActivity.this);
            }

            updateRadioBtnContent(0);
          }
        } else {
          toastShow(result.data);
          setTitle("生长发育测评");
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/growth_test/create", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  @SuppressWarnings("unused")
  private void showUnsubmitdialog() {
    View view = LayoutInflater.from(this)
        .inflate(R.layout.unfinishdialog, null);
    CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this)
        .setContentView(view)
        .setNegativeButton("确定放弃", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            finish();
          }
        }).setPositiveButton("继续完成", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });

    if (!isFinishing()) {
      cdb.create().show();
    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_next:

      if (pager < (totoalQuestionNum - 1)) {
        ++pager;

        JSONObject jsonObjCheck = new JSONObject();

        try {
          jsonObjCheck.put("question_id", question_id + "");
          jsonObjCheck.put("answer_id", id + "");
          jsonList.put(jsonObjCheck);
        } catch (JSONException e) {
          e.printStackTrace();
        }

        progressBar.setProgress(10 * (pager + 1));

        if (pager == totoalQuestionNum - 1) {
          btn_next.setText("提交");
        }

        setNextButtonEnable(false);
        updateRadioBtnContent(pager);
      } else {
        if (pager == totoalQuestionNum - 1) {
          btn_next.setText("提交");
        }

        // 提交答题
        JSONObject jsonObjCheck = new JSONObject();
        try {
          jsonObjCheck.put("question_id", question_id + "");
          jsonObjCheck.put("answer_id", id + "");
          jsonList.put(jsonObjCheck);
        } catch (JSONException e) {
          e.printStackTrace();
        }

        submitAnswer();
      }

      break;
    default:
      break;
    }
  }

  public void showNotificationTipDialog() {
    LayoutInflater inflater = getLayoutInflater();
    final View layout = inflater.inflate(R.layout.retest_dlg, null);// 获取自定义布局

    TextView tv_babyage = (TextView) layout.findViewById(R.id.tv_babyage);
    if (tv_babyage != null
        && Tools.isNotEmpty(LeXiaoXiaoBanApp.getInstance().kidAge)) {
      tv_babyage.setText("您的宝贝的年龄是" + LeXiaoXiaoBanApp.getInstance().kidAge
          + ",");
    }

    notificationTipDlg = new Dialog(this, R.style.custom_dialog);
    notificationTipDlg.setContentView(layout);
    notificationTipDlg.setCancelable(false);
    notificationTipDlg.show();

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        if (hasFinish) {
          if (notificationTipDlg != null) {
            notificationTipDlg.dismiss();
            notificationTipDlg = null;
          }

          // if (mTestResultDetail != null) {
          Intent intent = new Intent();
          // if (Tools.isNotEmpty(mTestResultDetail)) {
          // intent.putExtra("mTestResultDetail", mTestResultDetail);
          // }
          intent.putExtra("registerflow", isregisterflow);
          intent.putExtra("getScore", true); // 获取分数
          intent.setClass(AbilityTestActivity.this,
              com.jdy.haoduoai.activity.HistoryTestResultActivity.class);
          startActivity(intent);

          // }

          finish();
        }
      }
    }, 3000);
  }

  private Dialog notificationTipDlg;
  long prelongTim = 0;
  private boolean hasFinish;

  private void submitAnswer() {
    // showloading("");

    showNotificationTipDialog();

    prelongTim = System.currentTimeMillis();

    hasFinish = false;
    new CustomAsyncTask(this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {

        dismissLoading();
        hasFinish = true;
        long curTime = System.currentTimeMillis();
        if ((curTime - prelongTim) > 3200) {
          if (notificationTipDlg != null) {
            notificationTipDlg.dismiss();
            notificationTipDlg = null;
          }

          if (result.isSuccess()) {
            // mTestResultDetail = JsonSerializer.getInstance().deserialize(
            // result.data, LeTestResult.class);

            Intent intent = new Intent();
            if (startActivityForResult) {
              intent.putExtra("getScore", true); // 获取分数
              // intent.putExtra("mTestResultDetail", mTestResultDetail);
              setResult(RESULT_OK, intent);
              finish();
            } else {
              // if (Tools.isNotEmpty(mTestResultDetail)) {
              // intent.putExtra("mTestResultDetail", mTestResultDetail);
              // }
              intent.putExtra("registerflow", isregisterflow);
              intent.putExtra("getScore", true); // 获取分数
              intent.setClass(AbilityTestActivity.this,
                  com.jdy.haoduoai.activity.HistoryTestResultActivity.class);
              startActivity(intent);
            }
          } else {
            toastShow(result.data);
          }

          finish();
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("result", jsonList);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/growth_test", param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }
}
